package com.jerry.base.java8.lambda;

import java.util.ArrayList;
import java.util.List;

/**
 * 函数对象好处1：行为参数化
 *
 * @author Jerry
 * @since 2024/7/29 13:57
 */
public class Sample2 {

    public static void main(String[] args) {
        List<Student> students = List.of(
                new Student("张无忌", 18, "男"),
                new Student("杨不悔", 16, "女"),
                new Student("周芷若", 19, "女"),
                new Student("宋青书", 20, "男")
        );

        // 需求一：筛选男性学生
        System.out.println(filter0(students, student -> student.sex.equals("男")));

        // 需求二：筛选18岁以下的学生
        System.out.println(filter0(students, student -> student.age < 18));
    }

    interface Lambda {
        boolean test(Student student);
    }

    static List<Student> filter0(List<Student> students, Lambda filter) {
        List<Student> result = new ArrayList<>();
        for (Student student : students) {
            if (filter.test(student)) {
                result.add(student);
            }
        }
        return result;
    }

    static List<Student> filter(List<Student> students) {
        List<Student> result = new ArrayList<>();
        for (Student student : students) {
            if (student.sex.equals("男")) {
                result.add(student);
            }
        }
        return result;
    }

    static List<Student> filter2(List<Student> students) {
        List<Student> result = new ArrayList<>();
        for (Student student : students) {
            if (student.age < 18) {
                result.add(student);
            }
        }
        return result;
    }

    record Student(String name, Integer age, String sex) {
    }
}
